<template>
  <div class="chat-page">
        <div class="top">
            <div class="left" @click="showEdit">
                <img src="../assets/images/service_pic.png" alt="">
            </div>
            <div class="mid">
                <span>广场<i></i></span>
                <span>关注</span>
            </div>
            <div class="right">
                <img src="../assets/images/home_message.png" alt="">
            </div>
        </div>
        <div class="tallmsg" v-if="play">
            <div class="message">
                <div class="info" v-for="(item) in talkLists" :key="item.id" @click="showDetail(item.talk.id,item.talk.type)">
                    <div class="info_top">
                        <div class="person_info" @click.stop="showAuthor(item.talk.user.id,item.talk.type)">
                            <div class="toux">
                                <img :src="'https://pic.ecook.cn/web/'+item.talk.user.imageid+'.jpg!s1'" alt="">
                                <img class="v" src="../assets/images/v5.png" alt="" v-show="item.talk.user.star==5">
                                <img class="v" src="../assets/images/v4.png" alt="" v-show="item.talk.user.star==4">
                                <img class="v" src="../assets/images/v3.png" alt="" v-show="item.talk.user.star==3">
                                <img class="v" src="../assets/images/v2.png" alt="" v-show="item.talk.user.star==2">
                                <img class="v" src="../assets/images/v1.png" alt="" v-show="item.talk.user.star==1">
                            </div>
                            <div class="t">
                                <h4>{{item.talk.user.nickname}}</h4>
                                <span v-if="item.talk.description!=null">{{item.talk.description}}</span>
                                <span v-else>{{item.talk.publishtime | sendTime}}</span>
                            </div>
                        </div>
                        <div class="n">
                            <div :class="['check',{'isuserfollow':item.talk.isUserFollowed!=0}]">
                                <span v-if="item.talk.isUserFollowed==0">+关注</span>
                                <span class="isuserfollow" v-else>已关注</span>
                            </div>
                            <img class="popverIcon" src="../assets/images/zan_down.png" alt="" @click.stop="Popover(item.talk.user.id)">
                        </div>
                    </div>
                    <div class="info_mid" v-if="item.talk.attachment==null" >
                        <ul v-if="item.talk.imageids.length!=0">
                            <li v-for="(m,index) in item.talk.imageids" :key="index" @click.stop="showImgs(item.id,index)">
                                <div
                                class="img"
                                :style="{
                                    'background-image': 'url(https://pic.ecook.cn/web/'+m+'.jpg!wl280)',
                                }"
                                v-lazy:background-image="'https://pic.ecook.cn/web/'+m+'.jpg!wl280'"
                                v-show="flag"></div>
                            </li>
                        </ul>
                        <ul v-else>
                            <li v-for="(m,index) in item.talk.imgurls" :key="index" @click.stop="showImgs(item.id,index)">
                                <div
                                class="img" 
                                :style="{
                                    'background-image': 'url('+m+')',
                                }" 
                                v-lazy:background-image=m
                                v-show="flag"></div>
                            </li>
                        </ul>
                        <h4>{{item.talk.text}}</h4>
                    </div>
                    <div class="info_mid" v-else >
                        <ul>
                            <li  @click.stop="showAttachImgs(item.talk.attachment.imageid)">
                                <div
                                class="img"
                                :style="{
                                    'background-image': 'url(https://pic.ecook.cn/web/'+item.talk.attachment.imageid+'.jpg!wl280)',
                                }"
                                v-lazy:background-image="'https://pic.ecook.cn/web/'+item.talk.attachment.imageid+'.jpg!wl280'"
                                v-show="flag"></div>
                            </li>
                        </ul>
                        <h4>{{item.talk.text}}</h4>
                    </div>
                    <div class="info_bot">
                        <div class="bot-t">
                            <div class="inp" @click.stop="showSend(item.talk.id)">
                                <span>快捷回复</span>
                                <div class="emo">
                                    <img src="../assets/images/Expression_3.png" alt="">
                                    <img src="../assets/images/Expression_12.png" alt="">
                                    <img src="../assets/images/item_guanzhu_red.png" alt="">
                                </div>
                            </div>
                            <div class="zan" v-if="item.talk.isLiked==0" @click.stop="like(item.talk.id)">
                                <img src="../assets/images/chat_list_zan_def.png" alt="">
                                <span>点个赞</span>
                            </div>
                            <div class="zan" v-else @click.stop="like(item.talk.id)">
                                <img src="../assets/images/chat_list_zan_slt.png" alt="">
                                <span class="islike">已点赞</span>
                            </div>
                        </div>
                        <div class="bot-b">
                            <div class="b-left">
                                <span>{{item.talk.commentNum}}人评论</span>
                                <span>{{item.talk.likeNum}}人点赞</span>
                            </div>
                            <div class="b-right" v-if="item.talk.user.id==123564">
                                <van-icon name="delete-o" size='18px' @click.stop="delSimple(item.talk.id)" />
                            </div>
                        </div>
                        <div class="commentCon">
                            <ul class="commentlist" @click.stop="showSend(item.talk.id)">
                                <li v-for="c in item.talk.commentList.slice(0,3)" :key="c.id">
                                    <div class="username">{{c.user.nickname}}：</div>
                                    <div class="commentText">{{c.text}}</div>
                                </li>
                            </ul>
                            <div class="lookmore" v-if="item.talk.commentList.length>3" @click.stop="showDetail(item.talk.id,item.talk.type)">查看详细评论</div>
                        </div>
                    </div>
                </div>
                
            </div>
        </div>
        <bottom-tab :index=2 ></bottom-tab>
        <send-view v-if="showInp" @send="send" @close="close"></send-view>
        <van-image-preview v-model="showImg" :images="images" @change="onChange" :start-position="index" :swipe-duration="500" :loop="false">
            <template v-slot:index>{{ index+1 }}/{{images.length}}</template>
        </van-image-preview>
        <!-- 发布食话 -->
        <van-popup v-model="showPop" position="bottom" :style="{ height: '100%' }" >
            <div class="mainCon">
                <div class="SimpleTop">
                    <van-icon name="arrow-left" size="25" class="arrow-left" @click="showPop=false" />
                    <div class="SimpleTitle">编辑内容</div>
                    <div class="publishSimpleTalk" @click="publish">发布</div>
                </div>
                <div class="SimpleCom">
                    <textarea  v-model="areaTxt" cols="43" rows="3" class="area" placeholder="记录下你的美食点点滴滴"></textarea>
                    <div class="uploadImg">
                        <van-uploader v-model="fileList" multiple  :max-count="8">
                            <img class="uploadimg" src="../assets/images/bj_add.png" alt="">
                        </van-uploader>
                    </div>
                </div>
            </div>
        </van-popup>
  </div>
</template>

<script>
import SendView from '../components/SendView.vue'
import BottomTab from "../components/BottomTab.vue"
import {getCommunitySquareListData} from '../api/talk'
import { Dialog } from 'vant'
export default {
    data() {
        return {
            talkLists: null,
            show:-1,
            flag:true,
            showImg: false,
            index: 0,
            images: [],
            likelist:[],//点赞
            showInp:false,
            currentCom:null,//当前食话
            currentId:null,//当前食话ID
            comments:[],
            showPop:false,
            fileList: [],
            areaTxt:null,
            imgurls:[],
            SimpleTalkList:[],
            play:false

        };
    },
    methods: {
        //获取数据列表
        getCommunitySquareListFun(){
            getCommunitySquareListData().then(data=>{
                // console.log(data);
                if (data.list) {
                    this.play = true
                    data.list.forEach(item=>{
                        if (item.talk.imageids==null) {
                            item.talk.imageids = []
                        }
                        if (item.talk.imageids.length>9) {
                            item.talk.imageids = item.talk.imageids.split(",")
                        }else{
                            item.talk.imageids = [item.talk.imageids]
                        }
                        
                    })
                    this.talkLists = data.list

                    //重置发布
                    let tempTalk = JSON.parse(window.localStorage.getItem("SimplieTalkList"))
                    if (tempTalk) {
                        this.SimpleTalkList = tempTalk
                        this.SimpleTalkList.forEach(item=>{
                            this.talkLists.unshift(item)
                        })
                    }
                    //重置点赞
                    let templike = JSON.parse(window.localStorage.getItem("Simplelike"))
                    if (templike) {
                        this.likelist = templike
                        this.talkLists.forEach(item=>{
                            this.likelist.forEach(k=>{
                                if (item.talk.id==k.id) {
                                    item.talk.isLiked = 1,
                                    item.talk.likeNum = item.talk.likeNum+1
                                }
                            })
                        })
                    }
                    //重置评论
                    let tempComment = JSON.parse(window.localStorage.getItem("SimpleComment"))
                    if (tempComment) {
                        this.comments = tempComment
                        this.talkLists.forEach(item=>{
                            this.comments.forEach(m=>{
                                if (item.talk.id==m.talkid) {
                                    item.talk.commentList.unshift(m)
                                    item.talk.commentNum = item.talk.commentNum+1
                                }
                            })
                        })
                    }
                    //重置关注
                    let tempfollow = JSON.parse(window.localStorage.getItem("follows"))
                    if (tempfollow) {
                        this.talkLists.forEach(item=>{
                            tempfollow.forEach(k=>{
                                if (item.talk.user.id==k.id) {
                                    item.talk.isUserFollowed = 1
                                }
                            })
                        })
                    }
                    // console.log(this.talkLists);
                }
            })
        },
        //图片预览
        onChange(index) {
            this.index = index;
        },
        showImgs(id,i){
            this.showImg = true
            let index = this.talkLists.findIndex(item=>item.id==id)
            this.index = i
            this.images = []
            if (this.talkLists[index].talk.imageids.length!=0) {
                this.talkLists[index].talk.imageids.forEach(item=>{
                    this.images.push(
                        'https://pic.ecook.cn/web/'+item+'.jpg!wl720'
                    )
                }) 
            }else{
                this.talkLists[index].talk.imgurls.forEach(item=>{
                    this.images.push(item)
                })
            }
        },
        //图片展示
        showAttachImgs(img){
            this.showImg = true
            this.images = []
            this.images.push('https://pic.ecook.cn/web/'+img+'.jpg!wl720')
        },
        //作者详情
        showAuthor(id,type){
            if (type!='only') {
                this.$router.push({path:'/author',query:{id}})
            }else{
                this.$toast("暂时没有资料");
            }
        },
        //食话详情
        showDetail(id,type){
            if (type!='only') {
                this.$router.push({path:'/simpletalk',query:{id}})
            }else{
                this.$toast("暂时没有资料");
            }
        },
        //点赞
        like(id){
            let index = this.talkLists.findIndex(item=>item.talk.id==id)
            let i = this.likelist.findIndex(item=>item.id==id)
            this.talkLists[index].talk.isLiked = this.talkLists[index].talk.isLiked==0?1:0
            if (this.talkLists[index].talk.isLiked==1) {
                if (i==-1) {
                    this.likelist.push({
                        id
                    })
                }
                this.talkLists[index].talk.likeNum = this.talkLists[index].talk.likeNum+1
            }else{  
                this.talkLists[index].talk.likeNum = this.talkLists[index].talk.likeNum-1
                this.likelist.splice(i,1)
            }
            window.localStorage.setItem("Simplelike",JSON.stringify(this.likelist))
        },
        //评论
        send(value){
            if (value) {
                let userId = window.localStorage.getItem("userId");
                let comment = {
                    id:new Date().getTime(),
                    talkid:this.currentId,
                    text:value,
                    displaytime:null,
                    realtime:new Date().getTime(),
                    username:'厨友'+userId,
                    userimageid:"8877665544",
                    userid:userId,
                    replyComment:null,
                    likeNum:0,
                    liked:false,
                    user:{
                        id:userId,
                        nickname:'厨友'+userId,
                        userimageid:"8877665544",
                        star:0,
                        profile:'这家伙很懒，什么都没有留下',

                    }
                }
                this.comments.push(comment)
                window.localStorage.setItem("SimpleComment",JSON.stringify(this.comments))
                let index = this.talkLists.findIndex(item=>item.talk.id==this.currentId)
                this.talkLists[index].talk.commentList.unshift(comment)
                this.talkLists[index].talk.commentNum = this.talkLists[index].talk.commentNum+1
                this.showInp = false
            }
        },
        showSend(id){
            this.showInp = true
            let index = this.talkLists.findIndex(item=>item.talk.id==id)
            this.currentCom = this.talkLists[index]
            this.currentId = this.talkLists[index].talk.id
        },
        //关闭评论窗口
        close(value){
            this.showInp = value
        },
        //显示编辑界面
        showEdit(){
            this.showPop = true
        },
        //转URL
        base64ImgtoFile (dataurl, filename = 'file') {
            const arr = dataurl.split(',')
            const mime = arr[0].match(/:(.*?);/)[1]
            const suffix = mime.split('/')[1]
            const bstr = atob(arr[1])
            let n = bstr.length
            const u8arr = new Uint8Array(n)
            while (n--) {
              u8arr[n] = bstr.charCodeAt(n)
            }
            return new File([u8arr], `${filename}.${suffix}`, {
              type: mime
            })
        },
        //发布
        publish(){
            let userId = window.localStorage.getItem("userId");
            if (this.fileList.length!=0) {
                this.fileList.forEach(item=>{
                    let fileObj = this.base64ImgtoFile(item.content)
                    let imgurl = window.webkitURL.createObjectURL(fileObj) || window.URL.createObjectURL(fileObj)
                    this.imgurls.push(imgurl)
                })
                let SimpleTalk = {
                    id:String(new Date().getTime()),
                    talk:{
                        commentList:[],
                        commentNum:0,
                        description:null,
                        publishtime:new Date().getTime(),
                        id:String(new Date().getTime()),
                        imageids:[],
                        imgurls:this.imgurls,
                        isLiked:0,
                        isUserFollowed:0,
                        likeNum:0,
                        text:this.areaTxt,
                        top:0,
                        type:"only",
                        user:{
                            id:userId,
                            imageid:"8877665544",
                            nickname:'厨友'+userId,
                            star:0,
                            profile:'这家伙很懒，什么都没有留下',
                        },
                    },
                    type:0
                }
                this.talkLists.unshift(SimpleTalk)
                this.SimpleTalkList.push(SimpleTalk)
                window.localStorage.setItem("SimplieTalkList",JSON.stringify(this.SimpleTalkList))
                this.showPop = false
                this.areaTxt = ''
                this.fileList = []
                this.imgurls = []
                this.$toast("发布成功");
            }else{
                this.$toast("请选择至少一张图片");
            }
        },
        //关注作者
        addfollow(id){
            let index = this.talkLists.findIndex(item=>item.talk.user.id==id)
            this.talkLists[index].talk.isUserFollowed=this.talkLists[index].talk.isUserFollowed==0?1:0
            let tempfollow = JSON.parse(window.localStorage.getItem("follows"))
            tempfollow = tempfollow==null?[]:tempfollow
            let i = tempfollow.findIndex(item=>item.id==id)
            if (this.talkLists[index].talk.isUserFollowed==1) {
                if (i==-1) {
                    tempfollow.push({
                      id,
                      imageid:this.talkLists[index].talk.user.imageid,
                      profile:this.talkLists[index].talk.user.profile,
                      star:this.talkLists[index].talk.user.star,
                      name:this.talkLists[index].talk.user.nickname
                  })
                }
            }else{
                tempfollow.splice(i,1)
            }
            window.localStorage.setItem("follows",JSON.stringify(tempfollow))
        },
        //删除我发布的食话
        delSimple(id){
            Dialog.confirm({
                message: '确定删除该食话吗?',
                width:'260px',
                confirmButtonColor:'blue',
                confirmButtonText:'删除',
                cancelButtonColor:'blue'
            })
            .then(() => {
              let index = this.talkLists.findIndex(item=>item.talk.user.id==id)
              let arr = JSON.parse(window.localStorage.getItem("SimplieTalkList"))
              let i = arr.findIndex(item=>item.talk.user.id==id)
              this.talkLists.splice(index,1)
              arr.splice(i,1)
              window.localStorage.setItem("SimplieTalkList",JSON.stringify(arr))
              this.$toast("删除成功")
              console.log(this.talkLists);
            })
            .catch(() => {
              // on cancel
            });
        },
    },
    created() {
        window.localStorage.setItem("tabId",2)
        this.getCommunitySquareListFun()
    },
    components:{
      BottomTab,
      SendView
    },
    filters:{
        sendTime(value){
            let time = new Date()
            let times = time.getTime()
            let nowtime = times-value
            if (nowtime < 0) {

                return ''

            } else if ((nowtime / 1000 < 30)) {

                return '刚刚'

            } else if (nowtime / 1000 < 60) {

                return parseInt((nowtime / 1000)) + '秒前'

             } else if ((nowtime / 60000) < 60) {

                return parseInt((nowtime / 60000)) + '分钟前'

            } else if ((nowtime / 3600000) < 24) {

                return parseInt(nowtime / 3600000) + '小时前'

            } else if ((nowtime / 86400000) < 31) {

                return parseInt(nowtime / 86400000) + '天前'

            } else if ((nowtime / 2592000000) < 12) {

                return parseInt(nowtime / 2592000000) + '月前'

            } else {

                return parseInt(nowtime / 31536000000) + '年前'

            }
        }
    }
};
</script>

<style lang="less" scoped>
.chat-page{
    width: 100%;
    height: 100%;
    overflow: hidden;

    .top {
            height: 50px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid #ccc;
            background-color: #fff;
        
            .right,
            .left {
                width: 40px;
                height: 100%;
                margin-left: 10px;
                display: flex;
                justify-content: center;
                align-items: center;
        
                &>img {
                    width: 25px;
                    height: 20px;
                }
            }
        
            .right {
                margin-left: 0;
                margin-right: 10px;
            }
        
            .mid {
                width: 200px;
                height: 100%;
                display: flex;
                justify-content: space-evenly;
                align-items: center;
        
                &>span {
                    display: block;
                    width: 32px;
                    color: #999;
                    font-weight: 600;
                }
        
                &>span:first-child {
                    color: #f37748;
                    position: relative;
        
                    &>i {
                        display: block;
                        width: 20px;
                        height: 3.5px;
                        border-radius: 3px;
                        background-color: #f37748;
                        position: absolute;
                        bottom: -15px;
                        left: 5px;
                    }
                }
            }
    }
    
    .tallmsg{
        height: 100%;
        overflow-y: scroll;
       .message {
           margin-top: 20px;
           margin-bottom: 120px;
           .info {
             margin-bottom: 30px;
             .info_top {
                        width: 90%;
                        height: 60px;
                        margin: 0 auto;
                        display: flex;
                        justify-content: space-between;
            
                        .person_info {
                            display: flex;
                            align-items: center;
            
                            .toux{
                                width: 35px;
                                height: 35px;
                                position: relative;
                                z-index: 1;
                                &>img {
                                    width: 35px;
                                    height: 35px;
                                    display: block;
                                    border-radius: 50%;
                                }
                                .v{
                                    width: 15px;
                                    height: 15px;
                                    position: absolute;
                                    right: -4px;
                                    bottom: -3px;
                
                                }
                            }
            
                            .t {
                                margin-left: 10px;
            
                                &>h4 {
                                    font-size: 14px;
                                    font-weight: 600;
                                }
            
                                &>span {
                                    display: block;
                                    margin-top: 6px;
                                    color: #999;
                                    font-size: 12px;
                                }
                            }
                        }
            
                        .n {
                            display: flex;
                            align-items: center;
            
                            .popverIcon {
                                width: 40px;
                                height: 40px;
                            }
            
                            .check {
                                text-align: center;
                                color: #f37748;
                                font-weight: 700;
                                font-size: 14px;
                                padding: 5px 6px;
                                border-radius: 4px;
                                background-color: #fef3ef;
                            }
                            .isuserfollow{
                                color: #999;
                                background-color: #f2f2f2;
                            }
                        }
             }
    
             .info_mid {
                width: 90%;
                margin: 0 auto;
            
                &>ul {
                    width: 100%;
                    display: flex;
                    flex-wrap: wrap;
            
                    &>li {
                        // width: 100px;
                        height: 108px;
                        margin: 2px;
                        border-radius: 8px;
                        overflow: hidden;

                        .img{
                            width: 108px;
                            height: 100%;
                            background-image: url("../assets/images/picker_pic_default.png");
                            background-repeat: no-repeat;
                            background-position: center center;
                            background-size: cover;
                        }

                    }
                }
            
                &>h4 {
                    line-height: 22px;
                    margin: 10px 0 15px 0;
                    font-weight: 550;
                    font-size: 14px;
                }
             }
    
             .info_bot {
                        width: 90%;
                        margin: 0 auto;
            
                        .bot-t {
                            display: flex;
            
                            .inp {
                                width: 68%;
                                padding: 10px 15px;
                                border-radius: 15px;
                                background-color: #f7f7f7;
                                display: flex;
                                justify-content: space-between;
                                align-items: center;
            
                                &>span {
                                    color: #999;
                                    font-size: 12px;
                                    letter-spacing: 1.2px;
                                }
            
                                .emo {
                                    width: 100px;
                                    display: flex;
                                    justify-content: space-evenly;
            
                                    &>img {
                                        width: 15px;
                                        height: 15px;
                                    }
                                }
                            }
            
                            .zan {
                                display: flex;
                                align-items: center;
                                margin-left: 10px;
            
                                &>img {
                                    width: 15px;
                                    height: 15px;
                                    margin-right: 5px;
                                }
            
                                &>span {
                                    font-size: 14px;
                                    font-weight: 600;
                                }
                                .islike{
                                    color: #f37748;
                                }
                            }
                        }
            
                        .bot-b {
                            width: 100%;
                            margin-top: 15px;
                            display: flex;
                            font-size: 13px;
                            color: #999;
                            justify-content: space-between;
                            align-items: center;

                            .b-left{
                                display: flex;
                                &>span {
                                    display: block;
                                    margin-right: 15px;
                
                                }
                            }
            
                        }
                        .commentCon{
                            padding-top: 20px;
                            padding-left: 5px;
                            .commentlist{
                                &>li{
                                    display: flex;
                                    font-size: 13px;
                                    margin-bottom: 10px;
                                    .username{
                                        font-weight: bold;
                                    }
                                }
                            }
                            .lookmore{
                                font-size: 13px;
                                padding-top: 5px;
                                color: #f37748;
                            }
                        }
             }
           }
       }
        &::-webkit-scrollbar {
            display: none;
        }
    }
    .mainCon{
    
        .SimpleTop{
            width: 100%;
            height: 40px;
            border-bottom: 0.5px solid #ccc;
            display: flex;
            justify-content: space-between;
            align-items: center;

            .arrow-left{
                width: 28px;
            }
            .SimpleTitle{
                font-weight: 700;
                letter-spacing: 0.5px;
            }
            .publishSimpleTalk{
                font-size: 14px;
                color: #f37748;
                margin-right: 10px;
                font-weight: 700;
            }
        }
        .SimpleCom{
            padding-top: 10px;
            .area{
                box-sizing: border-box;
                border: none;
                font-size: 15px;
                padding: 10px;
                letter-spacing: 0.5px;
                line-height: 22px;
            }
            .uploadImg{
                padding: 5px 10px;
                .uploadimg{
                    width: 80px;
                    height: 80px;
                }
            }
        }
    }
}

</style>